import { postRequest, postRequestDownload } from '@/api/data'
import Vue from 'vue'
import { isArray } from '@/utils/validate'
import { camelCaseToLine } from '@/utils/index'

/* function getColumns(columns) {
  return {
    visible(columnField) {
      return !columns || !columns[columnField] ? true : columns[columnField].visible
    }
  }
}*/

function mergeOptions(src, target) {
  /* const optsRet = {
    src,
    ...opts
  }*/
  for (const key in src) {
    const notExist = !target[key] || (isArray(target[key]) && target[key].length === 0)
    if (notExist) { // || !target.hasOwnProperty(key)) {
      target[key] = src[key]
    }
  }
  return target
}

export default {
  data() {
    return {
      tableId: 'tableGridId',
      loading: true,
      pageCount: true,
      listSubmit: false,
      searchToggle: false,
      deleteLoading: false,
      changeLoading: false,
      submitLoading: false,
      destoryLoading: false,
      exportLoading: false,
      expandAll: false,
      data: [] || {},
      selectedGridRows: [],
      total: 0,
      url: '',
      params: {
        pageBean: { pageSize: 10, pageNo: 1, totalCount: 0 },
        orderBean: {}
      },
      paramBean: {},
      defaultParamBean: {},
      time: 170,
      queryMode: false,
      customProps: {}
    }
  },
  mounted() {
    /* const mainGridTable = this.getMainTable()
    this.customColumns = getColumns(columns)
    this.updateCustomProp('tableColumns', columns) */
  },
  methods: {
    getMainTable() {
      const _mainTable = this.$refs.mainTable
      if (_mainTable) {
        return _mainTable.$refs[_mainTable.tableRef]
      }
      return null
    },
    updateCustomProp(name, value) {
      Vue.set(this.customProps, name, value)
    },
    setPageNo(pageNo) {
      if (this.params.pageBean) {
        this.params.pageBean.pageNo = pageNo
      }
    },
    /**
     * 重置查询参数
     * @param {Boolean} toQuery 重置后进行查询操作
     */
    resetQuery(toQuery = true) {
      this.paramBean = JSON.parse(JSON.stringify(this.defaultParamBean))
      if (toQuery) {
        this.setPageNo(1)
        this.queryMode = false
        this.init()
      }
    },
    // 搜索
    toQuery() {
      this.setPageNo(1)
      this.queryMode = true
      this.init()
    },
    toggleSearch() {
      this.searchToggle = !this.searchToggle
    },
    async init() {
      if (!await this.beforeInit()) {
        return
      }
      if (!this.queryMode) this.paramBean = mergeOptions(this.defaultParamBean, this.paramBean)
      if (this.paramBean) {
        this.params['paramBean'] = this.paramBean
      }
      if (!this.pageCount) {
        this.params['pageBean'] = null
      }
      return new Promise((resolve, reject) => {
        this.loading = true
        postRequest(this.url, this.params).then(res => {
          if (res.data.pageBean) {
            this.total = res.data.pageBean.totalCount
          }
          this.data = res.data
          setTimeout(() => {
            this.loading = false
          }, this.time)
          this.afterInit(res)
          resolve(res)
        }).catch(err => {
          this.loading = false
          reject(err)
        })
      })
    },
    afterInit(res) {
    },
    beforeInit() {
      return true
    },
    pageChange(e) {
      this.setPageNo(e)
      this.init()
    },
    sizeChange(e) {
      this.setPageNo(1)
      this.params.pageBean.pageSize = e
      this.init()
    },
    gridSortChange({ column, prop, order }) {
      if (order) {
        this.params.orderBean.sortFields = [camelCaseToLine(prop)]
        this.params.orderBean.sortTypes = [order === 'ascending' ? 'ASC' : 'DESC']
      } else {
        this.params.orderBean = {}
      }
      this.init()
    },
    handleGridSelectionChange(val) {
      this.selectedGridRows = val
    },
    getSelectBusId() {
      const _this = this.sup_this
      const selectIds = []
      let selectId = ''
      _this.selectedGridRows.forEach(row => {
        selectIds.push(row.busId)
        selectId = row.busId
      })
      if (selectIds.length === 0 || selectIds.length > 1) {
        this.$message({
          message: '请选择一条记录',
          type: 'warning'
        })
        return null
      }
      return selectId
    },
    getSelectMainId() {
      const _this = this.sup_this
      const selectIds = []
      let selectId = ''
      _this.selectedGridRows.forEach(row => {
        selectIds.push(row.id)
        selectId = row.id
      })
      if (selectIds.length === 0 || selectIds.length > 1) {
        this.$message({
          message: '请选择一条记录',
          type: 'warning'
        })
        return null
      }
      return selectId
    },
    doMultiSubmit(submitUrl, sourceObject) {
      const _this = this
      const selectIds = []
      _this.selectedGridRows.forEach(row => {
        selectIds.push(row.id)
      })
      if (selectIds.length === 0) {
        this.$message({
          message: '请选择记录',
          type: 'warning'
        })
        return
      }
      sourceObject.submitLoading = true
      this.$confirm('确认要提交选中的记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        const data = { idList: selectIds, formSubmit: true }
        postRequest(submitUrl, data).then(res => {
          sourceObject.submitLoading = false
          _this.init()
        }).catch(err => {
          sourceObject.submitLoading = false
          console.log(err)
        })
      }).catch(() => {
        sourceObject.submitLoading = false
      })
    },
    doExport(exportUrl, sourceObject) {
      this.$confirm('确认要导出?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.exportLoading = true
        const exportData = JSON.parse(JSON.stringify(this.params))
        exportData['pageBean'] = null
        const exportFileName = Date.parse(new Date()) + '.xlsx'
        postRequestDownload(exportUrl, exportData, exportFileName).then(res => {
          this.exportLoading = false
        }).catch(err => {
          this.exportLoading = false
          console.log(err)
        })
      }).catch(() => {
        this.exportLoading = false
      })
    },
    doMultiDelete(deleteUrl, sourceObject) {
      const _this = this // .sup_this
      const selectIds = []
      _this.selectedGridRows.forEach(row => {
        selectIds.push(row.id)
      })
      if (selectIds.length === 0) {
        this.$message({
          message: '请选择记录',
          type: 'warning'
        })
        return
      }
      sourceObject.deleteLoading = true
      this.$confirm('确认要删除选中的记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        const data = { idList: selectIds }
        postRequest(deleteUrl, data).then(res => {
          sourceObject.deleteLoading = false
          _this.init()
        }).catch(err => {
          sourceObject.deleteLoading = false
          console.log(err)
        })
      }).catch(() => {
        sourceObject.deleteLoading = false
      })
    },
    doMultiDestory(destoryUrl, selectIds, isSubmit, sourceObject) {
      const _this = this
      sourceObject.destoryLoading = true
      const data = { idList: selectIds, listSubmit: isSubmit }
      postRequest(destoryUrl, data).then(res => {
        sourceObject.destoryLoading = false
        _this.init()
      }).catch(err => {
        sourceObject.destoryLoading = false
        console.log(err)
      })
      /* const h = this.$createElement
      this.$msgbox({
        title: '确认要注销选中的记录?',
        message: h('select', { class: 'detail', value: '0', on: { change: function(event) {
          if (event.target.selectedIndex === 1) {
            _this.listSubmit = true
          } else {
            _this.listSubmit = false
          }
        } }}, [
          h('option', { value: '0' }, '暂存'),
          h('option', { value: '1' }, '提交')
        ]),
        dangerouslyUseHTMLString: true,
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(action => { */
    },
    /**
     * 用于树形表格选中所有
     * @param selection
     */
    gridSelectAllChange(selection) {
      // 如果选中的数目与请求到的数目相同就选中子节点，否则就清空选中
      if (selection && selection.length === this.getMainTable().data.length) {
        selection.forEach(val => {
          this.gridCascadeSelectChange(selection, val)
        })
      } else {
        this.getMainTable().clearSelection()
      }
    },
    /**
     * 用于树形表格级联多选，单选的封装
     * @param selection
     * @param row
     */
    gridCascadeSelectChange(selection, row) {
      // 如果selection中存在row代表是选中，否则是取消选中
      if (selection.find(val => { return val.id === row.id })) {
        if (row.children) {
          row.children.forEach(val => {
            this.getMainTable().toggleRowSelection(val, true)
            selection.push(val)
            if (val.children) {
              this.gridCascadeSelectChange(selection, val)
            }
          })
        }
      } else {
        this.toggleRowSelection(selection, row)
      }
    },
    /**
     * 切换选中状态
     * @param selection
     * @param data
     */
    toggleRowSelection(selection, data) {
      if (data.children) {
        data.children.forEach(val => {
          this.getMainTable().toggleRowSelection(val, false)
          if (val.children) {
            this.toggleRowSelection(selection, val)
          }
        })
      }
    },
    /**
     * 用于树形表格折叠所有
     * @param selection
     */
    toggleTreeAllExpand() {
      const mainTable = this.getMainTable()
      const isExpand = !this.expandAll
      mainTable.data.forEach(val => {
        this.toggleTreeRowExpansion(val, isExpand)
      })
      this.expandAll = isExpand
    },
    toggleTreeRowExpansion(row, isExpand) {
      if (row.children) {
        const mainTable = this.getMainTable()
        mainTable.toggleRowExpansion(row, isExpand)
        row.children.forEach(val => {
          if (val.children) {
            mainTable.toggleRowExpansion(val, isExpand)
            this.toggleTreeRowExpansion(val, isExpand)
          }
        })
      }
    },
    /**
     * 用于查看历史版本记录
     * @param rowData
     * @param refComponentName
     */
    openViewHistory(rowData, refComponentName) {
      const _this = this.$refs[refComponentName]
      _this.sysGenCode = rowData.sysGenCode
      _this.init()
      _this.dialog = true
    }
  }
}
